﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
using DevExpress.XtraEditors;
using COMOSOFT.Class;
using COMOSOFT.JobManagement.Dataset;
using System.IO;
using DevExpress.XtraGrid.Views.Grid;
using System.Net.Mail;

namespace COMOSOFT.JobManagement.Froms
{
    public partial class FrmJobManagement : Form
    {
        #region [Init Form]
        int JID;
        ClassShare cls = new ClassShare("FrmJobManagement");
        Dataset.DataSet_JobManagementTableAdapters.JobAttachMentTableAdapter adt = new Dataset.DataSet_JobManagementTableAdapters.JobAttachMentTableAdapter();
        List<string> ListAttachFile = new List<string>();
        List<string> ListEmail = new List<string>();
        bool isrequester = false;
        DataTable dtbTo=new DataTable();
        string Assigner,mess,title;
        public FrmJobManagement(int _JID)
        {
            InitializeComponent();
            JID = _JID;
        }
        #endregion

        #region [Load Data]
        public void LoadData()
        {
            try
            {
                if (JID > 0)
                {
                    ListAttachFile.Clear();
                    this.jobAssignmentTableAdapter.Fill(this.dataSet_JobManagement.JobAssignment, JID);
                    this.sp_JobSubmiterListTableAdapter.Fill(this.dataSet_JobManagement.sp_JobSubmiterList, JID, 1,ClassShare.Usid);
                    this.jobFollowupTableAdapter.Fill(this.dataSet_JobManagement.JobFollowup, JID);
                    this.jobSubmiterTableAdapter.Fill(this.dataSet_JobManagement.JobSubmiter, ClassShare.Usid);
                    gridView_Actionlog.ExpandAllGroups();
                    JID =Convert.ToInt32(txt_JID.EditValue);
                    txt_To.CheckAll();
                    this.Text = txt_Subjects.Text;
                    DataTable dtb = adt.GetData(JID);
                    int numrow = dtb.Rows.Count;
                    if (numrow > 0)
                    {
                        for (int i = 0; i < numrow; i++)
                        {
                            ListAttachFile.Add(dtb.Rows[i]["Filename"].ToString());
                        }
                    }

                    this.employeeTableAdapter.Fill(this.dataSetOrderManagement.Employee);
                    this.sp_JobCheckingTableAdapter.Fill(this.dataSet_JobManagement.sp_JobChecking, JID);
                    this.sp_JobSubmiterStatusTableAdapter.Fill(this.dataSet_JobManagement.sp_JobSubmiterStatus, JID, ClassShare.Usid);
                    gridView_JobChecking.ExpandAllGroups();                    
                    //Check status 
                    DataTable dtbStatus = dataSet_JobManagement.sp_JobSubmiterStatus;
                    if (dtbStatus.Rows.Count > 0)
                    {
                        if (dtbStatus.Rows[0]["SubStatus"].ToString() == "Accept")
                        {
                            panel_Status.Enabled = false;
                            if (dtbStatus.Rows[0]["JobStatus"].ToString() == "Pending" || dtbStatus.Rows[0]["JobStatus"].ToString() == "Reject")
                                bnt_Finish.Visible = true;
                            if (dtbStatus.Rows[0]["JobStatus"].ToString() == "Waiting")
                                bnt_recall.Visible = true;
                        }
                        if (dtbStatus.Rows[0]["SubStatus"].ToString() == "" ||dtbStatus.Rows[0]["SubStatus"].ToString() =="Reject" )
                            dockPanel_Actionlog.Visibility = DevExpress.XtraBars.Docking.DockVisibility.Hidden;
                        if(dtbStatus.Rows[0]["JobStatus"].ToString() == "Finished")
                            panel_Status.Enabled = false;
                    }
                    DataTable dtbrequester = cls.GetData("sp_JobRequester", new string[] { "@JID", "@EID" }, new object[] { JID, ClassShare.Usid });
                    if (dtbrequester.Rows.Count > 0)
                    {
                        panel_Status.Visible = false;
                        if (dtbrequester.Rows[0]["Status"].ToString() == "Waiting")
                        {
                            panel_confirm.Visible = true;
                            isrequester = true;
                            this.sp_JobGetEmailSubmiterTableAdapter.Fill(this.dataSet_JobManagement.sp_JobGetEmailSubmiter, JID);
                        }
                    }  

                    DisplayAtachfiles();
                }
            }
            catch
            {
                MessageBox.Show("Disconnect database!", "Disconnect...", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        #endregion

        #region [Display Attachfiles]
        private void DisplayAtachfiles()
        {
            try
            {
                while (bnt_Attachment.Properties.Buttons.Count > 1)
                {
                    bnt_Attachment.Properties.Buttons.RemoveAt(0);
                }
                foreach (string fn in ListAttachFile)
                {
                    FileInfo finfo = new FileInfo(fn);
                    Image img = null;
                    if (finfo.Extension.ToLower() == ".pdf")
                    {
                        img = imageCollection1.Images[2];
                    }
                    else if (finfo.Extension.ToLower() == ".xls")
                    {
                        img = imageCollection1.Images[1];
                    }
                    else if (finfo.Extension.ToLower() == ".xlsx")
                    {
                        img = imageCollection1.Images[1];
                    }
                    else if (finfo.Extension.ToLower() == ".doc")
                    {
                        img = imageCollection1.Images[3];
                    }
                    else if (finfo.Extension.ToLower() == ".docx")
                    {
                        img = imageCollection1.Images[3];
                    }
                    else
                        img = imageCollection1.Images[0];

                    DevExpress.Utils.SerializableAppearanceObject serializableAppreanceObje = new DevExpress.Utils.SerializableAppearanceObject();
                    serializableAppreanceObje.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Underline);
                    serializableAppreanceObje.ForeColor = System.Drawing.Color.Blue;
                    serializableAppreanceObje.Options.UseFont = true;
                    serializableAppreanceObje.Options.UseForeColor = true;
                    DevExpress.XtraEditors.Controls.EditorButton b = new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Glyph, finfo.Name, -1, true, true, false, DevExpress.XtraEditors.ImageLocation.MiddleLeft, img, new DevExpress.Utils.KeyShortcut(System.Windows.Forms.Keys.None), serializableAppreanceObje, "", null, null, true);
                    b.Tag = fn;
                    bnt_Attachment.Properties.Buttons.Insert(0, b);
                }
                GC.Collect();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        #endregion

        #region [View File Attach]
        private void bnt_Attachment_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            try
            {
                if (e.Button.Tag.ToString() == "0")
                {
                    OpenFileDialog file = new OpenFileDialog();
                    file.Multiselect = true;
                    if (file.ShowDialog() == DialogResult.OK)
                    {
                        for (int i = 0; i < file.FileNames.Length; i++)
                        {
                            ListAttachFile.Add(file.FileNames[i]);
                        }
                        DisplayAtachfiles();
                    }                   
                }
                else
                    System.Diagnostics.Process.Start(e.Button.Tag.ToString());
            }
            catch
            {
                MessageBox.Show("Not find File Attach!", "Not Find...", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        #endregion

        #region[Form Load]
        private void FrmJobManagement_Load(object sender, EventArgs e)
        {
            //try
            //{
            //    this.employeeTableAdapter.Fill(this.dataSetOrderManagement.Employee);
            //    this.sp_JobCheckingTableAdapter.Fill(this.dataSet_JobManagement.sp_JobChecking, JID);
            //    this.sp_JobSubmiterStatusTableAdapter.Fill(this.dataSet_JobManagement.sp_JobSubmiterStatus, JID, ClassShare.Usid);
            //    gridView_JobChecking.ExpandAllGroups();
            //    popupContainerControl_Comment.Hide();
            //    //Check status 
            //    DataTable dtbStatus = dataSet_JobManagement.sp_JobSubmiterStatus;
            //    if (dtbStatus.Rows.Count > 0)
            //    {
            //        if (dtbStatus.Rows[0]["SubStatus"].ToString() == "Accept")
            //        {                        
            //            panel_confirm.Enabled = false;
            //            if (dtbStatus.Rows[0]["JobStatus"].ToString() == "Pending" || dtbStatus.Rows[0]["JobStatus"].ToString() == "Reject")
            //                bnt_Finish.Visible = true;
            //            if (dtbStatus.Rows[0]["JobStatus"].ToString() == "Waiting")               
            //                bnt_recall.Visible = true;                      
            //        }                    
            //    }
            //    DataTable dtbrequester = cls.GetData("sp_JobRequester", new string[] { "@JID", "@EID" }, new object[] { JID, ClassShare.Usid });
            //    if (dtbrequester.Rows.Count > 0)
            //    {
            //        panel_confirm.Visible = true;
            //        isrequester = true;
            //        this.sp_JobGetEmailSubmiterTableAdapter.Fill(this.dataSet_JobManagement.sp_JobGetEmailSubmiter, JID);
            //    }                
            //}
            //catch (Exception ex)
            //{
            //    MessageBox.Show(ex.Message);
            //}
        }
        #endregion

        #region [Update Job]

        public void AddNew()
        {
            jobAssignmentBindingSource.AddNew();
            txt_RequestDate.EditValue = DateTime.Now;
            txt_Status.Text = "Pending";
            this.employeeTableAdapter.Fill(this.dataSetOrderManagement.Employee);
            this.sp_JobSubmiterListTableAdapter.Fill(this.dataSet_JobManagement.sp_JobSubmiterList, JID, 0,ClassShare.Usid);
            txt_From.EditValue = Convert.ToInt64(ClassShare.Usid);  
        }
        public void UpdateJob()
        {
            try
            {                
                jobAssignmentBindingSource.EndEdit();
                jobAssignmentTableAdapter.Update(dataSet_JobManagement.JobAssignment);
                dataSet_JobManagement.JobAssignment.AcceptChanges();
                this.Text = txt_Subjects.Text;
                DataTable dtb = dataSet_JobManagement.JobAssignment;
                JID = Convert.ToInt32(dtb.Rows[0]["JID"]);

                List<object> listitem = new List<object>();
                listitem = txt_To.Properties.Items.GetCheckedValues();
                if (listitem.Count > 0)
                {
                    foreach (var item in listitem)
                    {
                        cls.UpdateData("sp_JobSubmiterInsert", new string[] { "@JID","@Assigner", "@EID"}, new object[] { JID,ClassShare.Usid, Convert.ToInt32(item)});
                    }
                }
                if (ListAttachFile.Count > 0)
                {
                    foreach (string att in ListAttachFile)
                    {
                        cls.UpdateData("sp_JobAttachMentUpdate", new string[] { "@JID", "@FileName", "@Type", "@Date" }, new object[] { JID, att, "document", DateTime.Now });
                    }
                }
                MessageBox.Show("<<< Send Job successfully >>>","Send Success",MessageBoxButtons.OK,MessageBoxIcon.Information);
                this.Close();
            }
            catch
            {
                MessageBox.Show("Not thing Update!!", "Update Fail", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        #endregion

        #region [InitNewRow]
        private void gridView_Actionlog_InitNewRow(object sender, DevExpress.XtraGrid.Views.Grid.InitNewRowEventArgs e)
        {


            try
            {
                GridView view = sender as GridView;
                view.SetFocusedRowCellValue("JID", JID);
                view.SetFocusedRowCellValue("Handler", ClassShare.Usid);
                view.SetFocusedRowCellValue("ActionDate", DateTime.Now);
            }
            catch
            {
                MessageBox.Show("Not Init new row!", "New row fail...", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        #endregion

        #region [Close Popup]
        private void dockPanel_Actionlog_ClosedPanel(object sender, DevExpress.XtraBars.Docking.DockPanelEventArgs e)
        {
            bnt_showdock.Visible = true;
        }
        #endregion

        #region[show popup]
        private void bnt_showdock_Click(object sender, EventArgs e)
        {      
            dockPanel_Actionlog.Show();                      
            bnt_showdock.Visible = false;
        }
        #endregion

        #region[Action log update]
        private void gridView_Actionlog_RowUpdated(object sender, DevExpress.XtraGrid.Views.Base.RowObjectEventArgs e)
        {
            try
            {
                jobFallowupBindingSource.EndEdit();
                jobFollowupTableAdapter.Update(dataSet_JobManagement.JobFollowup);
                dataSet_JobManagement.JobFollowup.AcceptChanges();
            }
            catch
            {
                MessageBox.Show("Not thing update!", "Update fail...", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        #endregion

        #region [Hide Button]
        public void CheckButton()
        {
            dockPanel_Actionlog.Visibility = dockPanel_Actionlog.Visibility = DevExpress.XtraBars.Docking.DockVisibility.Hidden;
            groupControl_Action.Visible = false;
        }
        #endregion       

        #region [Status Reject]
        private void bnt_OK_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Are you sure choose stattus?", "Choose Status...", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                cls.UpdateData("sp_JobSubmiterUpdate", new string[] { "@JID", "@EID", "@Status", "@Comment", "@flag" }, new object[] { JID, ClassShare.Usid, "Reject", txt_comment.Text, 1 });
                popupContainerControl_Comment.Hide();
                txt_comment.Text = "";
                mess = "Sorry! I can't make this job!";
                title = "Reject Job";
                SendMail();
            }
        }
        private void bnt_Cancel_Click(object sender, EventArgs e)
        {
            popupContainerControl_Comment.Hide();
            txt_comment.Text = "";
        }
        #endregion       

        #region [Send Email]
        public void SendMail()
        {
            try
            {               
                ListEmail.Clear();
                MailMessage message = new MailMessage();
                SmtpClient Client = new SmtpClient();
                Client.Host = "smtp.gmail.com";
                Client.Port = 587;
                Client.Credentials = new System.Net.NetworkCredential("dinhdongcntt@gmail.com", "Dong_OuIt@2711");
                Client.EnableSsl = true;
                Client.DeliveryMethod = SmtpDeliveryMethod.Network;
                message.From = new MailAddress(ClassShare.Email);
                message.Sender = new MailAddress(ClassShare.Email);
                sp_JobGetEmailTableAdapter.Fill(dataSet_JobManagement.sp_JobGetEmail, JID);
                //check submiter
                if (isrequester == true)
                {
                    dtbTo = dataSet_JobManagement.sp_JobGetEmailSubmiter;
                    if (dtbTo.Rows.Count > 0)
                    {
                        int numrow = dtbTo.Rows.Count;                      
                        for (int i=0;i< numrow; i++)
                        {                           
                           ListEmail.Add(dtbTo.Rows[i]["Email"].ToString());                                
                        }
                    }                    
                }
                else
                {
                    dtbTo = dataSet_JobManagement.sp_JobGetEmail;
                    if (dtbTo.Rows.Count > 0)
                    {
                        int numrow = dtbTo.Rows.Count - 1;
                        Assigner = dtbTo.Rows[numrow]["Assigner"].ToString();
                        ListEmail.Add(dtbTo.Rows[numrow]["Email"].ToString());
                        for (int i = numrow; i >= 0; i--)
                        {
                            if (Assigner == dtbTo.Rows[i]["EID"].ToString())
                            {
                                if (dtbTo.Rows[i]["Email"] != null && dtbTo.Rows[i]["Email"].ToString() != "")
                                    ListEmail.Add(dtbTo.Rows[i]["Email"].ToString());
                                Assigner = dtbTo.Rows[i]["Assigner"].ToString();
                            }
                        }
                    }
                }
                //-----------------------------------------------
                foreach (string item in ListEmail)
                {
                    message.To.Add(new MailAddress(item));
                }

                message.Subject = title;
                message.Body = mess +
                              " </br> Job Information: " +
                              " </br> Job Name: " + txt_Subjects.Text +
                              " </br> Job Contetn: " + txt_Content.Text +
                              " </br> Create Date: " + txt_RequestDate.EditValue.ToString();
                message.IsBodyHtml = true;  
                Client.Send(message);               
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                this.Close();
            }        
        }
        #endregion

        #region[Submit or Recall]

        private void bnt_Finish_Click(object sender, EventArgs e)
        {
            try
            {
                bnt_Finish.Enabled = false;               
                cls.UpdateData("sp_JobStatusUpdate", new string[] { "@JID", "@FinishDate", "@Status","@flag" }, new object[] { JID,DateTime.Now, "Waiting",0 });
                mess = "I finished my job!";
                title = "Finish job";
                SendMail();
                MessageBox.Show("congratulate, you had been finished your job!", "Finishing...", MessageBoxButtons.OK, MessageBoxIcon.Information);
                this.Close();
            }
            catch
            {
                MessageBox.Show("The Status not update", "Not Update...", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                this.Close();
            }
        }
        private void bnt_recall_Click(object sender, EventArgs e)
        {
            try
            {                
                cls.UpdateData("sp_JobStatusUpdate", new string[] { "@JID", "@FinishDate", "@Status", "@flag" }, new object[] { JID, DateTime.Now, "Pending", 0 });
                bnt_recall.Visible = false;
                LoadData();
                MessageBox.Show("Recall successfully!", "Recall...", MessageBoxButtons.OK, MessageBoxIcon.Information);               
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        #endregion      

        #region[ Update Submiter Status]
        private void bnt_statusok_Click(object sender, EventArgs e)
        {
            try
            {
                if (comboBoxEdit_JobStatus.SelectedIndex == 0)
                {
                    if (MessageBox.Show("Are you sure choose stattus?", "Choose Status...", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        cls.UpdateData("sp_JobSubmiterUpdate", new string[] { "@JID", "@EID", "@Status", "@Comment", "@flag" }, new object[] { JID, ClassShare.Usid, "Accept", "", 0 });
                        bnt_Finish.Visible = true;
                        mess = "I accept my job!";
                        title = "Accept Job";
                        SendMail();
                        this.Close();
                    }
                }
                else
                {
                   if (comboBoxEdit_JobStatus.SelectedIndex == 1)
                    {
                        popupContainerControl_Comment.Show();
                        mess = "Sorry! I Rejected my job!";
                        title = "Reject Job";
                        SendMail();
                    }
                    else
                    {
                        string title = txt_Subjects.Text;
                        string date = txt_RequestDate.EditValue.ToString();
                        string body = txt_Content.Text;
                        TabStatus tstt = new TabStatus(JID, title, date, body);
                        tstt.ShowDialog();
                    }
                }
                LoadData();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        #endregion

        #region [Reject-Approval]
        private void bnt_reject_Click(object sender, EventArgs e)
        {
            try
            {
                if (MessageBox.Show("Are you sure Reject this job?", "Rejecting...", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    cls.UpdateData("sp_JobStatusUpdate", new string[] { "@JID", "@FinishDate", "@Status","@flag" }, new object[] { JID, DateTime.Now, "Reject",0 });
                    mess = "Sorry! I can not approval this job";
                    title = "Reject job";
                    SendMail();
                }
            }
            catch
            {
                MessageBox.Show("You Can't reject this job!", "Can't Reject...", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void bnt_approval_Click(object sender, EventArgs e)
        {
            try
            {
                if (MessageBox.Show("Are you sure Approval this job?", "Approving...", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    cls.UpdateData("sp_JobStatusUpdate", new string[] { "@JID", "@FinishDate", "@Status","@flag" }, new object[] { JID, DateTime.Now, "Finished",1 });
                    mess = "I'm was Approved this job! Wish you success!";
                    title = "Approval job";
                    SendMail();
                }
            }
            catch
            {
                MessageBox.Show("You Can't Approval this job!", "Can't Approval...", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        #endregion       
    }  
}
